package com.zzw.controller;

import com.zzw.service.EmailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 邮件服务控制器
 * 提供邮件验证码发送和验证功能
 */
@Api(tags = "邮件服务接口")
@RestController
@RequestMapping("/api/email")
public class EmailController {

    @Autowired
    private EmailService emailService;

    /**
     * 发送验证码
     * @param email 接收者邮箱
     * @return 发送结果
     */
    @ApiOperation(value = "发送邮箱验证码", notes = "向指定邮箱发送验证码")
    @ApiImplicitParam(name = "email", value = "接收者邮箱", required = true, dataType = "String", paramType = "query")
    @GetMapping("/code/send")
    public Map<String, Object> sendVerificationCode(@RequestParam String email) {
        Map<String, Object> result = new HashMap<>();

        try {
            emailService.sendVerificationCode(email);
            result.put("code", 200);
            result.put("message", "验证码已发送，请查收邮箱");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "发送验证码失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 验证验证码
     * @param email 邮箱
     * @param code 验证码
     * @return 验证结果
     */
    @ApiOperation(value = "验证邮箱验证码", notes = "验证邮箱验证码是否正确")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "email", value = "邮箱", required = true, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/code/verify")
    public Map<String, Object> verifyCode(@RequestParam String email, @RequestParam String code) {
        Map<String, Object> result = new HashMap<>();

        boolean isValid = emailService.verifyCode(email, code);

        if (isValid) {
            result.put("code", 200);
            result.put("message", "验证成功");
        } else {
            result.put("code", 400);
            result.put("message", "邮箱验证码错误或已过期");
        }

        return result;
    }
}
